package servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.http.HttpResponse;
import com.google.gson.Gson;
import com.google.gson.annotations.JsonAdapter;
import model.*;
import service.AddressService;
import service.GoodsService;
import service.OrdersService;
import service.ShopCarService;
import service.impl.AddressServiceImpl;
import service.impl.GoodsServiceImpl;
import service.impl.OrderServiceImpl;
import service.impl.ShopCarServiceImpl;
import utils.BaseServlet;
import utils.DaoUtil;
import utils.DateUtil;
import utils.RandomUUID;
import vo.OrderVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author one world
 * @Date 2020/9/23 0023 16:55
 */
@WebServlet("/order")
public class OrderServlet extends BaseServlet {
    OrdersService service = new OrderServiceImpl();
    ShopCarService shopCarService = new ShopCarServiceImpl();
    GoodsService goodsService = new GoodsServiceImpl();
    AddressService addressService = new AddressServiceImpl();

    /**
     *查询我的订单
     * @param request
     * @param response
     * @throws IOException
     */
    public void toMyOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = (User)request.getSession().getAttribute("user");
        String stateStr = request.getParameter("state");
        int state = -1;
        if(stateStr!=null&&!stateStr.equals("")){
             state = Integer.parseInt(stateStr);
        }
        int id = user.getId();
        List<OrderVo> orders = service.findOrderInfo(id,state);
        PrintWriter out = response.getWriter();
        String result = JSONArray.toJSONString(orders);
        out.write(result);
        out.close();
    }

    /**
     * 后台管理员分页查询所有的订单
     * @param request
     * @param response
     * @throws IOException
     */
    public void findAllOrders(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String pageStr = request.getParameter("page");
        String pageLimit = request.getParameter("limit");
        if(pageStr==null||pageStr.equals("")){
            pageStr = "1";
        }
        if(pageLimit==null||pageStr.equals("")){
            pageLimit = "10";
        }
        List<OrderVo> orderVos = service.findAll(Integer.parseInt(pageStr),Integer.parseInt(pageLimit));
        int count = service.findCount();
        PrintWriter out = response.getWriter();
        Map map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",count);
        map.put("data",orderVos);
        out.write(JSON.toJSONString(map));
        out.close();
    }

    /**
     * 通过订单状态查询订单
     * @param request
     * @param response
     * @throws IOException
     */
    public void findAllByState(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String pageStr = request.getParameter("page");
        String pageLimit = request.getParameter("limit");
        if(pageStr==null||pageStr.equals("")){
            pageStr = "1";
        }
        if(pageLimit==null||pageStr.equals("")){
            pageLimit = "10";
        }
        List<OrderVo> orderVos = service.findAllByState(2,Integer.parseInt(pageStr),Integer.parseInt(pageLimit));
        int count = service.findCount();
        PrintWriter out = response.getWriter();
        Map map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",count);
        map.put("data",orderVos);
        out.write(JSON.toJSONString(map));
        out.close();
    }

    /**
     * 后台管理员查询退款订单
     * @param request
     * @param response
     * @throws IOException
     */
    public void findRefundOrders(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String pageStr = request.getParameter("page");
        String pageLimit = request.getParameter("limit");
        if(pageStr==null||pageStr.equals("")){
            pageStr = "1";
        }
        if(pageLimit==null||pageStr.equals("")){
            pageLimit = "10";
        }
        List<OrderVo> orderVos = service.findAllByState(2,Integer.parseInt(pageStr),Integer.parseInt(pageLimit));
        int count = service.findCount(2);
        PrintWriter out = response.getWriter();
        Map map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",count);
        map.put("data",orderVos);
        out.write(JSON.toJSONString(map));
        out.close();
    }

    /**
     * 订单创建
     * @param request
     * @param response
     * @throws IOException
     */
    public void createOrder(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String arr = request.getParameter("arr");
        User user =(User) request.getSession().getAttribute("user");
        List<String> array = JSONObject.parseArray(arr,String.class);
        List<Address> addresses = addressService.findByUserId(user.getId());
        if(addresses.size()==0){
            response.getWriter().write("请先添加收货地址！");
            return;
        }else{
            for(String s:array){
                ShopCar shopCar = shopCarService.findByPK(Integer.parseInt(s));
                Orders orders = new Orders();
                orders.setState(0);
                orders.setPayment(0);
                orders.setOrder_no(RandomUUID.getOrderNo());
                Goods goods = goodsService.findById(shopCar.getGoodsId());
                orders.setGoods(goods);
                orders.setNumber(shopCar.getCount());
                orders.setReal_price(shopCar.getPrice());
                orders.setTime(DateUtil.toDate(new Date()));
                orders.setUser(user);
                orders.setAddress(addresses.get(0));
                if(service.add(orders)){
                    shopCarService.delInfoById(Integer.parseInt(s));
                }
            }
            response.getWriter().write("true");
            response.getWriter().close();
        }
    }

    /**
     * 更改订单状态
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void changeOrderState(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String order_no = request.getParameter("order_no");
        String stateStr = request.getParameter("state");
        int state = 0;
        if(stateStr==null||stateStr.equals("")){
            return;
        }
        state = Integer.parseInt(stateStr);
        if(state==3&&service.updateOrderState(order_no,state)){
            response.sendRedirect("alipay?method=refund&order_no="+order_no);
        }else {
            if(service.updateOrderState(order_no,state)){
                response.getWriter().write(JSON.toJSONString("SUCCESS"));
            }else {
                response.getWriter().write(JSON.toJSONString("FAILED"));
            }
        }
    }

    /**
     * 删除订单信息
     * @param request
     * @param response
     * @throws IOException
     */
    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id=0;
        String idStr = request.getParameter("order_id");
        if(idStr==null||idStr.equals("")){
            return;
        }else {
            id = Integer.parseInt(idStr);
        }
        String result = "FAILED";
        PrintWriter out = response.getWriter();
        if(service.delById(id)){
            result = "SUCCESS";
        }
        out.write(JSON.toJSONString(result));
        out.close();

    }
}
